package com.example.customviewtouch.downfresh.view

import android.animation.ValueAnimator
import android.content.Context
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.TextView
import com.example.customviewtouch.R
import com.example.customviewtouch.downfresh.interfaces.IRefreshHeader
import com.example.customviewtouch.downfresh.interfaces.RefreshHeaderState


class ArrowRefreshHeader(context: Context?) :
    LinearLayout(context), IRefreshHeader {

    private val mContentLayout: LinearLayout
    private val mArrowImageView: ImageView

    private val mStatusTextView: TextView
    private val mProgressBar: ProgressBar
    private val mRotateUpAnim: RotateAnimation
    private val mRotateDownAnim: RotateAnimation
    private var mMeasuredHeight = 0
    private var mState = RefreshHeaderState.STATE_NORMAL

    init {
        val layoutParams = LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        layoutParams.setMargins(0, 0, 0, 0)
        this.layoutParams = layoutParams
        this.setPadding(0, 0, 0, 0)

        //将refreshHeader高度设置为0

        //将refreshHeader高度设置为0
        mContentLayout = (LayoutInflater.from(context).inflate(R.layout.refresh_header_item, null) as LinearLayout?)!!
        addView(mContentLayout, LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0))

        //初始化控件

        //初始化控件
        mArrowImageView = findViewById<ImageView>(R.id.ivHeaderArrow)
        mStatusTextView = findViewById<TextView>(R.id.tvRefreshStatus)
        mProgressBar = findViewById<ProgressBar>(R.id.refreshProgress)

        //初始化动画

        //初始化动画
        mRotateUpAnim = RotateAnimation(
            0.0f, -180.0f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f
        ).also {
            it.duration = 200
            it.fillAfter = true
        }

        mRotateDownAnim = RotateAnimation(
            -180.0f, 0.0f,
            Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f
        ).also {
            it.duration = 200
            it.fillAfter = true
        }


        //将mContentLayout的LayoutParams高度和宽度设为自动包裹并重新测量
        measure(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        mMeasuredHeight = measuredHeight //获得测量后的高度

    }
    override fun onRest() {
        setState(RefreshHeaderState.STATE_NORMAL)
    }

    override fun onPrepare() {
        setState(RefreshHeaderState.STATE_RELEASE_TO_REFRESH)
    }

    override fun onRefreshing() {
        setState(RefreshHeaderState.STATE_REFRESHING)
    }

    override fun onMove(offset: Float, sumOffSet: Float) {
        if (getHeaderVisibleHeight() > 0 || offset > 0) {
            setVisibleHeight(offset.toInt() + getHeaderVisibleHeight())
            // 不在更新状态
            if (mState <= RefreshHeaderState.STATE_RELEASE_TO_REFRESH) {
                if (getHeaderVisibleHeight() < mMeasuredHeight) {
                    onPrepare()
                } else {
                    onRest()
                }
            }
        }
    }

    override fun onRelease(): Boolean {
        var isOnRefresh = false
        val height = getHeaderVisibleHeight()
        if (height == 0) {
            isOnRefresh = false
        }
        if (height > mMeasuredHeight  && mState < RefreshHeaderState.STATE_REFRESHING) {
            setState(RefreshHeaderState.STATE_REFRESHING)
            isOnRefresh = true
        }

        if (mState == RefreshHeaderState.STATE_REFRESHING && height > mMeasuredHeight ) {
            smoothScrollTo(mMeasuredHeight )
        }

        if (mState != RefreshHeaderState.STATE_REFRESHING) {
            smoothScrollTo(0)
        }

        if (mState == RefreshHeaderState.STATE_REFRESHING) {
            smoothScrollTo(mMeasuredHeight )
        }

        return isOnRefresh
    }

    override fun refreshComplete() {
        setState(RefreshHeaderState.STATE_DONE)
        reset()
        Handler().postDelayed(Runnable { reset() }, 200)
    }

    override fun getHeadView(): View {
        return this
    }

    override fun getHeaderVisibleHeight(): Int {
        val lp = mContentLayout!!.layoutParams as LayoutParams
        return lp.height
    }

    private fun reset() {
        smoothScrollTo(0)
        setState(RefreshHeaderState.STATE_NORMAL)
    }

    /**
     * 设置刷新头部可见的高度
     *
     * @param height
     */
    private fun setVisibleHeight(height: Int) {
        val actualHeight = if (height < 0) {
             0
        } else height
        val lp = mContentLayout.layoutParams as LayoutParams
        lp.height = actualHeight
        mContentLayout.layoutParams = lp
    }


    //下拉之后，当正在刷新的时候，将位置从下拉到的位置恢复规定的位置的动画
    private fun smoothScrollTo(destHeight: Int) {
        val animator = ValueAnimator.ofInt(getHeaderVisibleHeight(), destHeight)
        Log.i("ZZZyt", "smoothScrollTo: " + getHeaderVisibleHeight())
        animator.setDuration(300).start()
        animator.addUpdateListener { animation -> setVisibleHeight(animation.animatedValue as Int) }
        animator.start()
    }

    private fun setState(state: RefreshHeaderState) {
        if (mState == state) {
            return
        }
        when (state) {
            RefreshHeaderState.STATE_NORMAL -> {
                if (mState == RefreshHeaderState.STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.startAnimation(mRotateDownAnim)
                }
                if (mState == RefreshHeaderState.STATE_REFRESHING) {
                    mArrowImageView.clearAnimation()
                }
                mStatusTextView.text = "下拉刷新"
            }
            RefreshHeaderState.STATE_RELEASE_TO_REFRESH -> {
                mArrowImageView.visibility = View.VISIBLE
                mProgressBar.visibility = INVISIBLE
                if (mState != RefreshHeaderState.STATE_RELEASE_TO_REFRESH) {
                    mArrowImageView.clearAnimation()
                    mArrowImageView.startAnimation(mRotateUpAnim)
                    mStatusTextView.text = "释放立即刷新"
                }
            }
            RefreshHeaderState.STATE_DONE -> {
                mArrowImageView.clearAnimation()
                mArrowImageView.visibility = INVISIBLE
                mProgressBar.visibility = INVISIBLE
                mStatusTextView.text = "刷新完成"
            }
            // 设置刷新态
            else -> {
                mArrowImageView.clearAnimation()
                mArrowImageView.visibility = INVISIBLE
                mProgressBar.visibility = VISIBLE
                smoothScrollTo(mMeasuredHeight)
                mStatusTextView.text = "正在刷新...";
            }
        }
        this.mState = state
    }

}